package com.uetoken.cn.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.ChildAccountAdapter;
import com.uetoken.cn.adapter.FundAssetDetailsAdapter;
import com.uetoken.cn.adapter.holder.AddChildAccountHolder;
import com.uetoken.cn.adapter.model.FundAssetDetailsModel;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.ConfigBean;
import com.uetoken.cn.bean.PurseInfoBean;
import com.uetoken.cn.bean.PurseListBean;
import com.uetoken.cn.bean.PurseListHisBean;
import com.uetoken.cn.bean.SubPursesBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.manager.UEDataManager;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.BlockchainUtils;
import com.uetoken.cn.utils.GlideApp;
import com.uetoken.cn.utils.Save2DecimalUtils;
import com.uetoken.cn.utils.UrlUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class FundAssetDetailsActivity extends BaseActivity implements WebResponse,
        AddChildAccountHolder.OnAddChildAccountClickListener, Handler.Callback,
        ChildAccountAdapter.MyItemClickListener {

    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.chart)
    LineChart mChart;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.noDataTv)
    TextView noDataTv;
    @BindView(R.id.limitTv)
    TextView mTvBalance;
    @BindView(R.id.tv_freeze)
    TextView mTvFreeze;
    @BindView(R.id.text1)
    TextView text1;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.text3)
    TextView text3;
    @BindView(R.id.view3)
    View view3;
    @BindView(R.id.bottomLayout)
    LinearLayout mBottomLayout;
    @BindView(R.id.details2)
    TextView mDetails2;
    @BindView(R.id.contentLayout)
    RelativeLayout mContentLayout;
    @BindView(R.id.subAccountIv)
    ImageView mSubAccountIv;
    @BindView(R.id.chartLayout)
    RelativeLayout mChartLayout;
    @BindView(R.id.limitLayout)
    RelativeLayout mLimitLayout;

    FundAssetDetailsAdapter mFundAssetDetailsAdapter;
    /**
     * 获取钱包历史网络请求码
     */
    private static final int NETWORK_REQUEST_PURSE_LIST_HIS = 10;
    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_SUB_PURSES = 11;
    /**
     * 获取钱包金额网络请求码
     */
    private static final int NETWORK_REQUEST_GET_PURSE = 12;
    /**
     * 钱包序号
     */
    private String mId;
    /**
     * 子钱包id
     */
    private String purseId;
    /**
     * 子钱包名字
     */
    private String purseName;
    /**
     * 子钱包余额
     */
    private String balance;
    /**
     * 子钱包冻结
     */
    private String freeze;
    /**
     * 子钱包业务（功能）
     */
    private String operation;
    /**
     * 获取交易记录的天数 ，默认“7”天
     */
    private String days = "7";
    /**
     * 出钱包类型 0=主钱包 1=子钱包(由接口ListSubPurse获得)
     */
    private String typeid = "1";
    /**
     * 子钱包图标
     */
    private String pursepic;
    /**
     * 可用余额格式化
     */
    private String balanceformat;
    /**
     * 交易中金额
     */
    private String transactionamount;
    /**
     * recyclerview要显示的历史交易记录数据
     */
    private List<FundAssetDetailsModel> mFundList;
    /**
     * 折线图要显示的数据
     */
    private List<PurseListHisBean.DataBean.PursedaystatisBean> pursedaystatis = new ArrayList<>();


    /**
     * 1.进货，2.出货，3.转账，4.出货历史
     */
    private String[] mPursePracticeStr;
    private AddChildAccountHolder mAddChildAccountHolder;
    private ChildAccountAdapter mChildAccountAdapter;
    private Handler mHandler;
    private PopupWindow mPopupWindow;
    private List<SubPursesBean.DataBean> mChildPurseList;
    private String stockinurl;//进货URL
    private String minPicUrl;//底部功能菜单按钮的小图标URL
    private String pagetransfer;//单个转账--提示说明
    private String pagetransfers;//多个转账--提示说明
    private String pagestockout;//出货--提示说明
    private String depositTip;//充币--提示说明
    private int pursetype;//钱包类型
    private String transferFeeTip;
    private int itemHeight;
    private int newScale;
    private int pursetypeid;
    private PurseListBean.DataBean mDataBean;
//    小数点后精度：
//    BTC 小数点后8位
//    ETH 小数点后5位
//    USDT 小数点后8位
//    EOS 小数点后4位
//    BCH 小数点后8位

    @Override
    public int getLayoutId() {
        return R.layout.activity_dp_asset;
    }

    @Override
    public void initView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        ButterKnife.bind(this);
        mHandler = new Handler(this);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        mDataBean = (PurseListBean.DataBean) intent.getSerializableExtra("assetsDetailModel");
        pursetype = mDataBean.getPursetype();
        mId = mDataBean.getId() + "";
        purseId = mDataBean.getPurseid() + "";
        purseName = mDataBean.getPursename();
        balance = mDataBean.getBalance() + "";
        freeze = mDataBean.getFreeze() + "";
        operation = mDataBean.getOperation();
        pursepic = mDataBean.getPursepic();
        pursetypeid = mDataBean.getPursetypeid();
        balanceformat = mDataBean.getBalanceformat();
        transactionamount = mDataBean.getTransactionamount();
        int[] purseInfo = BlockchainUtils.getPurseIcon(purseName);
        newScale = purseInfo[1];

        String config = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");
        LogUtils.dTag("config==", "config== " + config);
        if (!TextUtils.isEmpty(config)) {
            Gson gson = new Gson();
            ConfigBean.DataBean dataBean = gson.fromJson(config, ConfigBean.DataBean.class);
            if (dataBean != null) {
                stockinurl = dataBean.getStockinurl();
                if (!TextUtils.isEmpty(stockinurl)) {
                    stockinurl = new String(EncodeUtils.base64Decode(stockinurl));
                }
                minPicUrl = dataBean.getMinpicurl();
                if (!TextUtils.isEmpty(minPicUrl)) {
                    minPicUrl = new String(EncodeUtils.base64Decode(minPicUrl));
                }
                pagetransfer = dataBean.getPagetransfer();
                if (!TextUtils.isEmpty(pagetransfer)) {
                    pagetransfer = new String(EncodeUtils.base64Decode(pagetransfer));
                }
                pagetransfers = dataBean.getPagetransfers();
                if (!TextUtils.isEmpty(pagetransfers)) {
                    pagetransfers = new String(EncodeUtils.base64Decode(pagetransfers));
                }
                pagestockout = dataBean.getPagestockout();
                if (!TextUtils.isEmpty(pagestockout)) {
                    pagestockout = new String(EncodeUtils.base64Decode(pagestockout));
                }
                depositTip = dataBean.getDeposittip();
                if (!TextUtils.isEmpty(depositTip)) {
                    depositTip = new String(EncodeUtils.base64Decode(depositTip));
                }
                transferFeeTip = dataBean.getTransferfeetip();
                if (!TextUtils.isEmpty(transferFeeTip)) {
                    transferFeeTip = new String(EncodeUtils.base64Decode(transferFeeTip));
                }
            }
        }

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentLayout.getLayoutParams();
        int bottomMargin = getResources().getDimensionPixelSize(R.dimen.album_dp_45);
        if ("".equals(operation) || operation == null || "null".equals(operation)) {
            layoutParams.bottomMargin = 0;
        } else {
            layoutParams.bottomMargin = bottomMargin;
        }
        mContentLayout.setLayoutParams(layoutParams);
//        getData();
        initTopBar();
        initRecyclerView();
        LogUtils.dTag("operation==", "operation== " + operation);
//        operation = "1,3";
        initBottomLayout();
        initPopupView();
    }

    @Override
    public void init() {

    }

    private void getData() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getPurseListHistoryUrl(Constant.MIAN_PURSE_HIS), NETWORK_REQUEST_PURSE_LIST_HIS,
                Params.getPurseListHistoryParams(purseId, days, "0", Constant.MIAN_PURSE_HIS));
    }

    private void getSubPurses() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getSubPursesUrl(), NETWORK_REQUEST_SUB_PURSES,
                Params.getSubPursesParams(purseId));
    }

    private void getPurse() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getPurseUrl(), NETWORK_REQUEST_GET_PURSE,
                Params.getPurseParams(purseId));
    }

    private void addBottomBtn(int backgroundColor, String picUrl, String text, int tag) {
        final TextView bottomBtn = new TextView(this);
        //设置权重
        bottomBtn.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        bottomBtn.setCompoundDrawablePadding(10);
        bottomBtn.setGravity(Gravity.CENTER);
        bottomBtn.setTextColor(ContextCompat.getColor(this, R.color.app_color_common_white));
        bottomBtn.setTextSize(14);
        RelativeLayout childLayout = new RelativeLayout(this);
        childLayout.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f));
        childLayout.setGravity(Gravity.CENTER);
        childLayout.addView(bottomBtn);


        childLayout.setBackgroundColor(ContextCompat.getColor(this, backgroundColor));
        GlideApp.with(FundAssetDetailsActivity.this).asBitmap().load(picUrl).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.picMeasure);
                LogUtils.dTag("openBidevent==", "openBidevent== spacingInPixels = " + spacingInPixels);
                resource = zoomBitmap(resource, spacingInPixels, spacingInPixels);
                BitmapDrawable drawable = new BitmapDrawable(getResources(), resource);

//                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                bottomBtn.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            }
        });
        bottomBtn.setText(text);
        childLayout.setTag(tag);
        childLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int val = (int) v.getTag();
                bottomStartActivity(val);
            }
        });
        mBottomLayout.addView(childLayout);
    }

    private void bottomStartActivity(int val) {
        Intent intent;
        switch (val) {
            case 1:
                String stockUrl = stockinurl + "?" + UrlUtils.getUrlParamsByMap(Params.getStockParams(mId));
                toWebActivity(stockUrl);
                break;
            case 2:
                intent = new Intent(FundAssetDetailsActivity.this, ShipmentNewActivity.class);
                intent.putExtra("balance", balance);
                intent.putExtra("purseId", purseId);
                intent.putExtra("purseName", purseName);
                intent.putExtra("freeze", freeze);
                intent.putExtra("pagestockout", pagestockout);
                intent.putExtra("pursepic", pursepic);
                startActivity(intent);
                break;
            case 3:
                intent = new Intent(FundAssetDetailsActivity.this, TransferAccountsActivity.class);
                intent.putExtra("assetsDetailModel", mDataBean);
                intent.putExtra("depositTip", depositTip);
                intent.putExtra("freeze", pursetypeid != 3 ? freeze : transactionamount);
                intent.putExtra("pagetransfer", pagetransfer);
                intent.putExtra("pagetransfers", pagetransfers);
                intent.putExtra("isChildPurse", false);
                intent.putExtra("transferFeeTip", transferFeeTip);

//                intent.putExtra("balance", balance);
//                intent.putExtra("frompurseId", purseId);
//                intent.putExtra("purseName", purseName);
//                intent.putExtra("freeze", freeze);
//                intent.putExtra("typeid", typeid);
//                intent.putExtra("pursetypeid",pursetypeid);
//                intent.putExtra("pagetransfer", pagetransfer);
//                intent.putExtra("pagetransfers", pagetransfers);
//                intent.putExtra("transferPurseName", purseName);
//                intent.putExtra("isChildPurse", false);
//                intent.putExtra("pursepic", pursepic);
                startActivity(intent);
                break;
            case 4:
                intent = new Intent(FundAssetDetailsActivity.this, HistoryActivity.class);
                intent.putExtra("purseId", purseId);
                intent.putExtra("historyType", Constant.STOCK_OUT_HIS);
                intent.putExtra("pursetypeid", pursetypeid);
                startActivity(intent);
                break;
            case 5:
                break;
            case 6:
                intent = new Intent(FundAssetDetailsActivity.this, ExchangeActivity.class);
                intent.putExtra("assetsDetailModel", mDataBean);
                startActivity(intent);
                break;
            case 7:
                intent = new Intent(FundAssetDetailsActivity.this, ChargeMoneyActivity.class);
                intent.putExtra("assetsDetailModel", mDataBean);
                intent.putExtra("depositTip", depositTip);
                startActivity(intent);
                break;
            case 8:
                intent = new Intent(FundAssetDetailsActivity.this, MentionMoneyActivity.class);
                intent.putExtra("assetsDetailModel", mDataBean);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void initBottomLayout() {
        int[] colors = new int[]{R.color.color_app_theme, R.color.cambridgeBlueColor, R.color.saxeBlueColor, R.color.colorPrimary, R.color.color_app_theme, R.color.color_app_theme, R.color.color_app_theme, R.color.cambridgeBlueColor};
        //1=进货（web页面），2=出货，3=转账，4=出货历史，5=充值，6=兑换
        mPursePracticeStr = new String[]{getResources().getString(R.string.stock_title_txt), getResources().getString(R.string.str_shipment_btn), getResources().getString(R.string.transfer_accounts_txt), getResources().getString(R.string.str_stockout_history), getResources().getString(R.string.str_recharge), getResources().getString(R.string.str_exchange), getResources().getString(R.string.str_charge_money), getResources().getString(R.string.str_mention_money)};
        String[] operationStr = operation.split(",");
        for (int i = 0; i < operationStr.length; i++) {
            int val = -1;
            try {
                val = Integer.parseInt(operationStr[i]);
                if (val <= mPursePracticeStr.length) {
                    String text = mPursePracticeStr[val - 1];
                    String picUrl = minPicUrl + val + ".png";
                    int color = colors[val - 1];
                    addBottomBtn(color, picUrl, text, val);
                }

            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    private void initTopBar() {
        mTopbar.setTitle(purseName);
        String freezeText;
        if (pursetypeid == 3) {
            mSubAccountIv.setVisibility(View.GONE);
            freezeText = getString(R.string.str_in_trading) + " " + transactionamount;
            text1.setText(getString(R.string.str_charge_money));
            text2.setText(getString(R.string.str_mention_money));
            text3.setVisibility(View.VISIBLE);
            view3.setVisibility(View.VISIBLE);
            mTvBalance.setText(balanceformat);
        } else {
            text1.setText(getString(R.string.str_shift_to));
            text2.setText(getString(R.string.rollout));
            text3.setVisibility(View.GONE);
            view3.setVisibility(View.GONE);
            mSubAccountIv.setVisibility(View.VISIBLE);
            freezeText = getString(R.string.str_freeze) + " " + freeze;
            mTvBalance.setText(balance);
        }
        mTvFreeze.setText(freezeText);
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void setLineChart() {
        mChart.getDescription().setEnabled(false);
        mChart.setDrawGridBackground(false);
        // 不显示y轴右边的值
        mChart.getAxisRight().setEnabled(false);
//        支持触控手势
        mChart.setTouchEnabled(true);
//        支持缩放和拖动
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(false);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(true);
        xAxis.setDrawAxisLine(true);


        xAxis.setLabelCount(6, false);
        //设置x轴label
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String[] dates = new String[pursedaystatis.size()];
                for (int i = 0; i < pursedaystatis.size(); i++) {
                    String time = pursedaystatis.get(i).getCreatetime();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        // 用parse方法，可能会异常，所以要try-catch
                        Date date = format.parse(time);
                        // 获取日期实例
                        Calendar calendar = Calendar.getInstance();
                        // 将日历设置为指定的时间
                        calendar.setTime(date);
                        // 这里要注意，月份是从0开始。
                        int month = calendar.get(Calendar.MONTH);
                        // 获取天
                        int day = calendar.get(Calendar.DAY_OF_MONTH);
                        dates[i] = month + 1 + "/" + day;
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                return String.valueOf(dates[(int) value % dates.length]);
            }
        });

        // 不显示图例
        Legend legend = mChart.getLegend();
        legend.setEnabled(false);

        YAxis yAxis = mChart.getAxisLeft();
        // 不显示y轴
        yAxis.setDrawAxisLine(true);
        // 设置y轴数据的位置
        yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        // 不从y轴发出横向直线
        yAxis.setDrawGridLines(false);
//        yAxis.setTextColor(Color.BLACK);
//        yAxis.setTextSize(12);
//        // 设置y轴数据偏移量
//        yAxis.setXOffset(15);
//        yAxis.setYOffset(-3);
//        yAxis.setAxisMinimum(0.00f);
//        yAxis.setLabelCount(5);
        yAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
//                BigDecimal mBigDecimal = new BigDecimal(value);
//                mBigDecimal = mBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
//                return String.valueOf(mBigDecimal);
                return "";
            }
        });
        mChart.setData(generateDataLine(30));
        // 绘制网格线
        mChart.setDrawGridBackground(false);
        // 绘制边框
        mChart.setDrawBorders(false);
        mChart.setNoDataText(getResources().getString(R.string.no_data));
        mChart.animateX(750);
        // 向左偏移15dp，抵消y轴向右偏移的30dp
        mChart.setExtraLeftOffset(-15);
        //适应屏幕
        mChart.fitScreen();
        mChart.setVisibleXRange(6, 6);
        mChart.invalidate();
    }

    /**
     * generates a random ChartData object with just one DataSet
     *
     * @return
     */
    private LineData generateDataLine(int cnt) {
        float data1 = 0;
        float data2 = 0;
        float data3 = 0;
        int color1 = 0;
        int color2 = 0;
        int color3 = 0;
        ArrayList<ILineDataSet> sets = new ArrayList<>();
        ArrayList<Entry> e1 = new ArrayList<>();
        if (pursedaystatis.size() != 0) {
            for (int i = 0; i < pursedaystatis.size(); i++) {
                if (pursetypeid == 3) {
                    color1 = getResources().getColor(R.color.redColor1);
                    data1 = Float.parseFloat(pursedaystatis.get(i).getTxsxf());
                } else {
                    color1 = getResources().getColor(R.color.azureColor);
                    data1 = Float.parseFloat(pursedaystatis.get(i).getSr());
                }
                e1.add(new Entry(i, data1));
            }
        }
        LineDataSet d1 = new LineDataSet(e1, "New DataSet " + cnt + ", (1)");
        d1.setLineWidth(2.5f);
        d1.setCircleRadius(0f);
        d1.setHighlightEnabled(false);
        d1.setColor(color1);
        d1.setDrawValues(true);
        d1.setDrawCircles(false);
        d1.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                String valueTxt;
                if (pursetypeid == 3) {
                    valueTxt = pursedaystatis.get((int) entry.getX()).getTxsxf() + "";
                } else {
                    valueTxt = pursedaystatis.get((int) entry.getX()).getSr() + "";
                }
                if (value <= 0) {
                    valueTxt = "0";
                }

                return valueTxt;
            }
        });
        sets.add(d1);

        ArrayList<Entry> e2 = new ArrayList<>();
        for (int i = 0; i < pursedaystatis.size(); i++) {
            if (pursetypeid == 3) {
                color2 = getResources().getColor(R.color.azureColor);
                data2 = Float.parseFloat(pursedaystatis.get(i).getCb());
            } else {
                color2 = getResources().getColor(R.color.cambridgeBlueColor);
                data2 = Float.parseFloat(pursedaystatis.get(i).getZc());
            }
            e2.add(new Entry(i, data2));
        }

        LineDataSet d2 = new LineDataSet(e2, "New DataSet " + cnt + ", (2)");
        d2.setLineWidth(2.5f);
        d2.setCircleRadius(0f);
        d2.setColor(color2);
        d2.setHighlightEnabled(false);
        d2.setDrawCircles(false);
        d2.setDrawValues(true);
        d2.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                String valueTxt;
                if (pursetypeid == 3) {
                    valueTxt = pursedaystatis.get((int) entry.getX()).getCb() + "";
                } else {
                    valueTxt = pursedaystatis.get((int) entry.getX()).getZc() + "";
                }
                return valueTxt;
            }
        });
        sets.add(d2);

        if (pursetypeid == 3) {
            ArrayList<Entry> e3 = new ArrayList<>();
            for (int i = 0; i < pursedaystatis.size(); i++) {
                data3 = Float.parseFloat(pursedaystatis.get(i).getTx());
                e3.add(new Entry(i, data3));
                color3 = getResources().getColor(R.color.cambridgeBlueColor);
            }

            LineDataSet d3 = new LineDataSet(e3, "New DataSet " + cnt + ", (3)");
            d3.setLineWidth(2.5f);
            d3.setCircleRadius(0f);
            d3.setColor(color3);
            d3.setHighlightEnabled(false);
            d3.setDrawCircles(false);
            d3.setDrawValues(true);
            d3.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                    String valueTxt = pursedaystatis.get((int) entry.getX()).getTx() + "";
                    return valueTxt;
                }
            });
            sets.add(d3);
        }
        LineData cd = new LineData(sets);
        return cd;
    }

    private void initRecyclerView() {
        mFundList = new ArrayList<>();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mFundAssetDetailsAdapter = new FundAssetDetailsAdapter(R.layout.fund_asset_item, mFundList);

        mRecyclerView.setVisibility(View.VISIBLE);
        noDataTv.setVisibility(View.GONE);
        mRecyclerView.setAdapter(mFundAssetDetailsAdapter);
    }

    private void initPopupView() {
        View view = null;
        if (mAddChildAccountHolder == null) {
            view = LayoutInflater.from(this).inflate(R.layout.add_child_account_popup, null);
            mAddChildAccountHolder = new AddChildAccountHolder(view);
            view.setTag(mAddChildAccountHolder);
        } else {
            mAddChildAccountHolder = (AddChildAccountHolder) view.getTag();
        }
        mAddChildAccountHolder.setOnAddChildAccountClickListener(this);

        mChildAccountAdapter = new ChildAccountAdapter(this);
        mAddChildAccountHolder.mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mAddChildAccountHolder.mRecyclerView.setAdapter(mChildAccountAdapter);
        mChildAccountAdapter.setMyItemClickListener(this);
        itemHeight = getResources().getDimensionPixelSize(R.dimen.album_dp_45);
        mAddChildAccountHolder.mRecyclerView.setMinimumHeight(itemHeight);

        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
    }

    private void showPopView() {
        if (mPopupWindow == null) {
            initPopupView();
        }
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
            int[] location = new int[2];
            mSubAccountIv.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标，含statusBar
            int leftMargin = location[0];
            int width = SizeUtils.getMeasuredWidth(mSubAccountIv);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mAddChildAccountHolder.mArrowUp.getLayoutParams();
            params.leftMargin = leftMargin - width / 2;
            mAddChildAccountHolder.mArrowUp.setLayoutParams(params);
//
//            View mView = LayoutInflater.from(this).inflate(R.layout.item_child_account_view, null);
            int popupHeight = SizeUtils.getMeasuredHeight(mAddChildAccountHolder.mPopupLayout);
            int popupMaxHeight = ScreenUtils.getScreenWidth();
            if (popupHeight > popupMaxHeight) {
                RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mAddChildAccountHolder.mPopupLayout.getLayoutParams();
                layoutParams1.height = popupMaxHeight;
                mAddChildAccountHolder.mPopupLayout.setLayoutParams(layoutParams1);
                mAddChildAccountHolder.mContentLayout.setBackgroundResource(R.drawable.white_circular_bead_shape);

                RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) mAddChildAccountHolder.mContentLayout.getLayoutParams();
                layoutParams2.height = popupMaxHeight - itemHeight;
                mAddChildAccountHolder.mContentLayout.setLayoutParams(layoutParams2);
            }
            RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) mAddChildAccountHolder.mAddAccountLayout.getLayoutParams();
            layoutParams3.height = itemHeight;
            mAddChildAccountHolder.mAddAccountLayout.setLayoutParams(layoutParams3);
            mAddChildAccountHolder.mAddAccountLayout.setBackgroundResource(R.drawable.white_circular_bead_shape);
            mPopupWindow.setWidth((ScreenUtils.getScreenWidth() - SizeUtils.dp2px(20)));
            mPopupWindow.showAtLocation(mSubAccountIv, Gravity.NO_GRAVITY, SizeUtils.dp2px(10), location[1] + mSubAccountIv.getHeight());
        }
    }

    @OnClick({R.id.subAccountIv, R.id.details2})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.subAccountIv:
                getSubPurses();
                break;
            case R.id.details2:
                intent = new Intent(FundAssetDetailsActivity.this, HistoryActivity.class);
                intent.putExtra("purseId", purseId);
                intent.putExtra("historyType", Constant.MIAN_PURSE_HIS);
                intent.putExtra("pursetypeid", pursetypeid);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("onSuccessResponse==", "onSuccessResponse== response = " + response);
        dissmissDialog();
        switch (requestCode) {
            case NETWORK_REQUEST_SUB_PURSES:
                SubPursesBean mSubPursesBean = new Gson().fromJson(response, SubPursesBean.class);
                if (mSubPursesBean.getResult() > 0) {
                    try {
                        List<SubPursesBean.DataBean> mChildPurseList = mSubPursesBean.getData();
                        Message message = new Message();
                        message.what = Constant.HANDLER_MESSAGE_WHAT_1100;
                        message.obj = mChildPurseList;
                        mHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showShort(mSubPursesBean.getMessage());
                    }
                } else {
                    ToastUtils.showShort(mSubPursesBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_PURSE_LIST_HIS:
                PurseListHisBean purseListHisBean = new Gson().fromJson(response, PurseListHisBean.class);
                if (purseListHisBean.getResult() > 0) {
                    PurseListHisBean.DataBean dataBean = purseListHisBean.getData();
                    List<PurseListHisBean.DataBean.PursehisBean> pursehisBeanList = dataBean.getPursehis();
                    pursedaystatis = dataBean.getPursedaystatis();
                    refreshRecyclerview(pursehisBeanList);
                    //设置折线图
                    if (pursedaystatis.size() != 0) {
                        setLineChart();
                    }

                } else {
                    ToastUtils.showShort(purseListHisBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_GET_PURSE:
                PurseInfoBean mPurseInfoBean = new Gson().fromJson(response, PurseInfoBean.class);
                if (mPurseInfoBean.getResult() > 0) {
                    PurseInfoBean.DataBean mPurseData = mPurseInfoBean.getData();
                    if (mPurseData != null) {
                        balance = mPurseData.getBalance();
                        freeze = mPurseData.getFreezevalue();
                        balanceformat = mPurseData.getBalanceformat();
                        transactionamount = mPurseData.getTransactionamount();

                        String freezeText;
                        if (pursetypeid == 3) {
                            mTvBalance.setText(balanceformat);
                            freezeText = getString(R.string.str_in_trading) + " " + transactionamount;
                        } else {
                            mTvBalance.setText(balance);
                            freezeText = getString(R.string.str_freeze) + " " + freeze;
                        }
                        mTvFreeze.setText(freezeText);
                    }
                } else {
                    ToastUtils.showShort(mPurseInfoBean.getMessage());
                }

                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    /**
     * 刷新recyclerview数据
     */
    private void refreshRecyclerview(List<PurseListHisBean.DataBean.PursehisBean> pursehis) {
        if (mFundList != null) {
            mFundList.clear();
        }
        for (int i = 0; i < pursehis.size(); i++) {
            PurseListHisBean.DataBean.PursehisBean pursehisBean = pursehis.get(i);
            FundAssetDetailsModel mFundAssetDetailsModel = new FundAssetDetailsModel();
            String balance;
            String balanceafter;
            if (pursetypeid == 3) {
                balance = pursehisBean.getBalanceformat();
                balanceafter = pursehisBean.getBalanceafterformat();
            } else {
                balance = pursehisBean.getBalance();
                balanceafter = pursehisBean.getBalanceafter();
            }
            mFundAssetDetailsModel.setWithdrawDeposit(pursehisBean.getRemarks());
            mFundAssetDetailsModel.setTimeWithdraw(pursehisBean.getCreatetime());
            mFundAssetDetailsModel.setTypeid(pursehisBean.getTypeid());
            mFundAssetDetailsModel.setMoney(balance);
            mFundAssetDetailsModel.setBalanceafter(balanceafter);
            mFundAssetDetailsModel.setIsShowBalance(true);

            mFundList.add(mFundAssetDetailsModel);
        }
        if (mFundList.size() <= 0) {
            noDataTv.setVisibility(View.VISIBLE);
        } else {
            noDataTv.setVisibility(View.GONE);
        }
        mFundAssetDetailsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onAddChildAccountClick(View view) {
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
        Intent intent = new Intent(FundAssetDetailsActivity.this, AddChildPurseActivity.class);
        intent.putExtra("purseId", purseId);
        startActivity(intent);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Constant.HANDLER_MESSAGE_WHAT_1100:
                mChildPurseList = (List<SubPursesBean.DataBean>) msg.obj;
                mChildAccountAdapter.setData(mChildPurseList);
                showPopView();
                break;
        }
        return false;
    }

    @Override
    public void onItemClick(View view, int postion) {
        mPopupWindow.dismiss();
        UEDataManager.getInstance().setChildPurseList(mChildPurseList);
        Intent intent = new Intent(FundAssetDetailsActivity.this, ChildPurseAssetActivity.class);
        intent.putExtra("postion", postion);
        intent.putExtra("purseId", purseId);
        intent.putExtra("purseName", purseName);
        intent.putExtra("pagetransfer", pagetransfer);
        intent.putExtra("pagetransfers", pagetransfers);
        intent.putExtra("pursepic", pursepic);
        intent.putExtra("pursetypeid", pursetypeid);
        startActivity(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        getPurse();
        getData();
    }

    /**
     * 跳转到webActivity
     *
     * @param url
     */
    private void toWebActivity(String url) {
        Intent intent = new Intent(FundAssetDetailsActivity.this, WebActivity.class);
        intent.putExtra(Constant.TO_WEBVIEW_URL, url);
        startActivity(intent);
    }

    //网络加载成功更改tv drawable图片：
    private void openBidevent(final TextView textView, String picUrl, String text) {
        GlideApp.with(FundAssetDetailsActivity.this).asBitmap().load(picUrl).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.picMeasure);
                LogUtils.dTag("openBidevent==", "openBidevent== spacingInPixels = " + spacingInPixels);
                resource = zoomBitmap(resource, spacingInPixels, spacingInPixels);
                BitmapDrawable drawable = new BitmapDrawable(getResources(), resource);

//                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            }
        });
//                .into(new SimpleTarget<Bitmap>() {
//            @Override
//            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                BitmapDrawable drawable = new BitmapDrawable(getResources(), resource);
//                /// 这一步必须要做,否则不会显示.                  drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
//                textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
//            }
//        });
        textView.setText(text);
    }

    //Bitmap缩放
    public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }
}
